<script setup lang="ts">
import { CaretUpOutlined, CaretDownOutlined } from '@ant-design/icons-vue';
import type { EquipmentInventorySlotInfoItem } from '../../../../game/model/inventory/type';
import { EVENTS, GameKernel } from '../../../../game';
import { rarityTextColorClass } from '../../../../utils';
import { computed, onMounted } from 'vue';
import { useEquipmentPanel } from '../../../../composables';
import EquipmentSlot from '../components/slot.vue';
import { ItemReader } from '../../../../game/systems/item/reader';
import { AttributesReader } from '../../../../game/systems/attributes/reader';
import { ATTRIBUTE_TYPE_ORDER } from '../../../../game/model/attributes/type';

const props = defineProps<{ item: EquipmentInventorySlotInfoItem }>();
const emit = defineEmits<{
  (e: 'close'): void;
}>();

const { state: equipmentPanelState } = useEquipmentPanel();

/** 未装备 */
const currentEquipmentIns = computed(() => {
  return props.item.ins;
});
const currentEquipmentConfig = computed(() => {
  return props.item.itemConfig;
});
const comparedAttributes = computed(() => {
  const currentAttrs =
    currentEquipmentIns.value?.payload?.equip?.baseAttrs || [];
  const equippedAttrs =
    equippedEquipmentIns.value?.payload?.equip?.baseAttrs || [];

  // 创建属性映射，确保按属性类型匹配
  const equippedAttrMap = new Map();
  equippedAttrs.forEach((attr) => {
    equippedAttrMap.set(attr.prop, attr.value);
  });

  const currentAttrMap = new Map();
  currentAttrs.forEach((attr) => {
    currentAttrMap.set(attr.prop, attr.value);
  });

  // 合并所有出现的属性类型，确保顺序一致
  const allProps = new Set([
    ...currentAttrs.map((attr) => attr.prop),
    ...equippedAttrs.map((attr) => attr.prop),
  ]);

  // 转换为数组并按照固定顺序排序（可选）
  const sortedProps = Array.from(allProps).sort((a, b) => {
    const indexA = ATTRIBUTE_TYPE_ORDER.indexOf(a);
    const indexB = ATTRIBUTE_TYPE_ORDER.indexOf(b);

    // 如果都在排序列表中，按列表顺序
    if (indexA !== -1 && indexB !== -1) {
      return indexA - indexB;
    }
    // 如果只有一个在列表中，在列表中的排在前面
    if (indexA !== -1) return -1;
    if (indexB !== -1) return 1;
    // 都不在列表中，按字母顺序
    return a.localeCompare(b);
  });

  return sortedProps
    .map((prop) => {
      const currentValue = currentAttrMap.get(prop) || 0;
      const equippedValue = equippedAttrMap.get(prop) || 0;
      const diff = currentValue - equippedValue;

      return {
        prop,
        name: AttributesReader.getAttributeName(prop),
        currentValue,
        equippedValue,
        diff,
        changeType: diff > 0 ? 'increase' : diff < 0 ? 'decrease' : 'same',
      };
    })
    .filter((attr) => attr.currentValue !== 0 || attr.equippedValue !== 0); // 过滤掉两个值都为0的属性
});
/** 已装备 */
const equippedEquipmentIns = computed(() => {
  return equipmentPanelState.value.slots[
    currentEquipmentConfig.value.equipSlot
  ];
});
const equippedEquipmentConfig = computed(() => {
  return equipmentPanelState.value.slotsConfig[
    currentEquipmentConfig.value.equipSlot
  ];
});
const equippedComparedAttributes = computed(() => {
  const currentAttrs =
    currentEquipmentIns.value?.payload?.equip?.baseAttrs || [];
  const equippedAttrs =
    equippedEquipmentIns.value?.payload?.equip?.baseAttrs || [];

  const currentAttrMap = new Map();
  currentAttrs.forEach((attr) => {
    currentAttrMap.set(attr.prop, attr.value);
  });

  const equippedAttrMap = new Map();
  equippedAttrs.forEach((attr) => {
    equippedAttrMap.set(attr.prop, attr.value);
  });

  const allProps = new Set([
    ...currentAttrs.map((attr) => attr.prop),
    ...equippedAttrs.map((attr) => attr.prop),
  ]);

  const sortedProps = Array.from(allProps).sort((a, b) => {
    const indexA = ATTRIBUTE_TYPE_ORDER.indexOf(a);
    const indexB = ATTRIBUTE_TYPE_ORDER.indexOf(b);

    // 如果都在排序列表中，按列表顺序
    if (indexA !== -1 && indexB !== -1) {
      return indexA - indexB;
    }
    // 如果只有一个在列表中，在列表中的排在前面
    if (indexA !== -1) return -1;
    if (indexB !== -1) return 1;
    // 都不在列表中，按字母顺序
    return a.localeCompare(b);
  });

  return sortedProps
    .map((prop) => {
      const currentValue = currentAttrMap.get(prop) || 0;
      const equippedValue = equippedAttrMap.get(prop) || 0;
      const diff = equippedValue - currentValue; // 注意这里是反向计算

      return {
        prop,
        name: AttributesReader.getAttributeName(prop),
        equippedValue,
        currentValue,
        diff: -diff, // 反向计算，便于显示
        changeType: diff > 0 ? 'decrease' : diff < 0 ? 'increase' : 'same',
      };
    })
    .filter((attr) => attr.equippedValue !== 0 || attr.currentValue !== 0); // 过滤掉两个值都为0的属性
});

function onEquipClick() {
  GameKernel.inst.bus.emit(EVENTS.EQUIPMENT_PANEL_EQUIP, props.item.ins);
}

function onSellClick() {
  GameKernel.inst.bus.emit(EVENTS.INVENTORY_SELL, props.item.ins, 1);
}

onMounted(() => {
  [
    EVENTS.INVENTORY_SELL_COMPLETED,
    EVENTS.INVENTORY_USE_COMPLETED,
    EVENTS.EQUIPMENT_PANEL_EQUIP_COMPLETED,
  ].forEach((eventName) => {
    GameKernel.inst.bus.on(eventName, () => {
      emit('close');
    });
  });
});
</script>

<template>
  <div v-if="props.item" class="cultivation-skill-detail">
    <div class="flex flex-col gap-1">
      <a-card v-if="equippedEquipmentIns" size="small" title="已装备">
        <div class="flex gap-2">
          <div class="flex-none">
            <equipment-slot :equipment="equippedEquipmentIns">
              <div v-if="equippedEquipmentConfig">
                {{ equippedEquipmentConfig.name }}
              </div>
            </equipment-slot>
            <div
              v-if="equippedEquipmentConfig?.equipSlot"
              class="text-center text-xs pt-1"
            >
              [{{
                ItemReader.getEquipSlotName(equippedEquipmentConfig.equipSlot)
              }}]
            </div>
          </div>
          <div class="flex-1">
            <div class="flex items-center">
              <div
                v-if="equippedEquipmentIns?.payload?.equip?.rarity"
                :class="
                  rarityTextColorClass(
                    equippedEquipmentIns.payload.equip.rarity
                  )
                "
              >
                【{{
                  ItemReader.getItemRarityName(
                    equippedEquipmentIns.payload.equip.rarity
                  )
                }}】{{ equippedEquipmentConfig?.name }}
              </div>
            </div>
            <div class="w-1/2">
              <div
                v-for="attr in equippedComparedAttributes"
                :key="attr.prop"
                class="flex items-center justify-between pl-2"
              >
                <div>{{ attr.name }}</div>
                <div class="flex items-center">
                  <div>{{ attr.equippedValue }}</div>
                  <div class="w-4 flex items-center justify-center"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="equippedEquipmentConfig?.canSell !== false"
          class="flex items-center justify-end text-xs"
        >
          <div>出售价格：</div>
          <div>{{ equippedEquipmentConfig?.basePrice }}</div>
        </div>
      </a-card>
      <a-card size="small">
        <template #title>
          <div class="flex items-center justify-between">
            <div>未装备</div>
            <div>
              <a-button
                v-if="props.item.itemConfig.canSell !== false"
                size="small"
                @click="onSellClick"
              >
                出售
              </a-button>
            </div>
          </div>
        </template>
        <div class="flex gap-2">
          <div class="flex-none">
            <equipment-slot :equipment="currentEquipmentIns">
              <div v-if="currentEquipmentConfig">
                {{ currentEquipmentConfig.name }}
              </div>
            </equipment-slot>
            <div class="text-center text-xs pt-1">
              [{{
                ItemReader.getEquipSlotName(currentEquipmentConfig.equipSlot)
              }}]
            </div>
          </div>
          <div class="flex-1">
            <div class="flex items-center">
              <div
                v-if="currentEquipmentIns.payload?.equip?.rarity"
                :class="
                  rarityTextColorClass(currentEquipmentIns.payload.equip.rarity)
                "
              >
                【{{
                  ItemReader.getItemRarityName(
                    currentEquipmentIns.payload?.equip?.rarity
                  )
                }}】{{ currentEquipmentConfig.name }}
              </div>
            </div>
            <div class="w-1/2">
              <div
                v-for="attr in comparedAttributes"
                :key="attr.prop"
                class="flex items-center justify-between pl-2"
              >
                <div>{{ attr.name }}</div>
                <div class="flex items-center">
                  <div>{{ attr.currentValue }}</div>
                  <div class="w-4 flex items-center justify-center">
                    <caret-up-outlined
                      class="text-[#00c954]"
                      v-if="attr.changeType === 'increase'"
                    />
                    <caret-down-outlined
                      class="text-[#f52e38]"
                      v-if="attr.changeType === 'decrease'"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="currentEquipmentConfig.canSell !== false"
          class="flex items-center justify-end text-xs"
        >
          <div>出售价格：</div>
          <div>{{ currentEquipmentConfig.basePrice }}</div>
        </div>
      </a-card>
    </div>
    <div class="pt-2">
      <div class="flex items-center justify-center gap-2">
        <a-button @click="onEquipClick">装备</a-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cultivation-skill-detail :deep(.ant-input-number-input) {
  text-align: center;
}
</style>
